package corp.sunny.commons.util.security;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

import org.apache.log4j.Logger;

/**
 * @File:JAASUtil.java
 * @Date:Jun 10, 2011
 * @Author:Subhash Bavi
 * 
 * @Description: JAAS Utility which is used for JAAS Security, creating login
 *               context and other security related stuff
 * @Copyright Sunny Corporation - 2011
 */
public class JAASUtil {

	private static final Logger LOG = Logger.getLogger(JAASUtil.class);
	private static LoginContext loginContext;
	private static JAASPrincipal principal;

	/**
	 * returns the JAAS Principal object
	 * 
	 * @throws LoginException
	 */
	public static JAASPrincipal getJAASPrincipal(String user, String passwd)
			throws LoginException {
		try {
			JAASPrincipal jaasPrincipal = new JAASPrincipal(user, passwd);
			Subject subject = new Subject();
			subject.getPrincipals().add(jaasPrincipal);

			loginContext = new LoginContext("SSOLoginModule", subject);
			LOG.info("LoginContext created: " + loginContext);

			// Attempt login
			loginContext.login();
			LOG.info("User Authentication Successful");

			principal = (JAASPrincipal) loginContext.getSubject()
					.getPrincipals().iterator().next();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JAASUtil.principal;
	}

	/**
	 * returns the JAAS Principal Object for a given GUID. Usually used by other
	 * applications integrated with SSO
	 * 
	 * @param guid
	 * @return String
	 * @throws LoginException
	 */
	public static JAASPrincipal getJAASPrincipal(String guid)
			throws LoginException {

		return null;
	}
}
